package by.grsu.bso.persistence.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import by.grsu.bso.model.Order;
import by.grsu.bso.persistence.base.IOrderDAO;
import by.grsu.bso.persistence.util.DaoManager;

public class OrderDAO extends DaoManager implements IOrderDAO {
	
	private static final String SAVE_ORDER_QUERY = "INSERT INTO shopdb.Order(UserID, StatusID, Date, Time) VALUES(?, ?, ?, ?);"; 
	private static final String FIND_ORDER_BY_ID_QUERY = "SELECT OrderID, UserID, StatusID, Date, Time FROM shopdb.Order WHERE OrderID = ?;";
	@Override
	public List<Order> get() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Order findById(int id) throws SQLException {

		Connection conn = getConnection();
		
		Order order = null;

		PreparedStatement stmt = conn.prepareStatement(OrderDAO.FIND_ORDER_BY_ID_QUERY);
		stmt.setInt(1, id);
		ResultSet rs = stmt.executeQuery();
		if (rs.next()) {
			order = new Order(  rs.getInt("OrderID"),
								rs.getInt("UserID"), 
								rs.getInt("StatusID"), 
								rs.getString("Date"), 
								rs.getString("Time"));
		}

		closeConnection(conn, rs, stmt);
		
		return order;
	}

	@Override
	public List<Order> findAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Order> findByExample(Order exampleInstance) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int countAll() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int countByExample(Order exampleInstance) {
		// TODO Auto-generated method stub
		return 0;
	}


	@Override
	public Order save(Order entity) throws SQLException {
		
		Connection conn = getConnection();
		Order order = null;

		PreparedStatement stmt = conn.prepareStatement(OrderDAO.SAVE_ORDER_QUERY, Statement.RETURN_GENERATED_KEYS);
		stmt.setInt(1, entity.getUserId());
		stmt.setInt(2, entity.getStatus());
		stmt.setString(3, entity.getDate());
		stmt.setString(4, entity.getTime());
		
		int affectedRows = stmt.executeUpdate();
		if (affectedRows == 0) {
			throw new SQLException("Creating user failed, no rows affected.");
		}
		ResultSet rs = stmt.getGeneratedKeys();
		int autoIncKey = 0;
		if (rs.next()) {
			autoIncKey = rs.getInt(1); // return id
		}
		order = findById(autoIncKey);

		closeConnection(conn, rs, stmt);

		return order;
	}

	@Override
	public Order create() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void delete(int id) {
		// TODO Auto-generated method stub
		
	}

}
